<template>
  <div class="container">
      <Header></Header>
      <div class="bg_img">
          <img class="logoImg" src="//yanxuan.nosdn.127.net/static-union/164793255107785e.png">
      </div>

      <div class="content">
          <van-form @submit="onSubmit">
              <van-cell-group inset>
                  <van-field v-model="phone" placeholder="请输入手机号"
                      :rules="[{ pattern, required: true, message: '手机号不合法' }]" />
                  <van-field v-model="code" center clearable placeholder="请输入短信验证码"
                      :rules="[{ required: true, message: '请获取验证码' }]">
                      <template #button>
                          <van-button @click="getCode" size="small" color="#999">发送验证码</van-button>
                      </template>
                  </van-field>

                  <van-field v-model="password" type="password" placeholder="请输入密码"
                      :rules="[{ required: true, message: '请输入密码' }]" />
                  <van-field v-model="confirmPwd" type="password" placeholder="请再次输入密码"
                      :rules="[{ required: true, message: '密码不一致' }]" />
              </van-cell-group>
              <div style="margin: 16px;">
                  <van-button block color="#dd1a21" native-type="submit">
                      立即注册
                  </van-button>
              </div>
          </van-form>
      </div>
  </div>
</template>

<script setup lang="ts">
import Header from '@/pages/Header/Header.vue';
import { reqUserCode, reqUserRegister } from '@/api/login/userinfo';
import { ref } from 'vue';
import router from '@/router';

// 响应式数据
const phone = ref('');
const password = ref('');
const confirmPwd = ref('');
const code = ref('');
// 手机号正则
const pattern = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;

// 获取验证码回调
const getCode = async () => {
  try {
      if (phone.value) {
          let result: any = await reqUserCode(phone.value);
          code.value = result.data;
      }
  } catch (error) {
      console.log(error);
  }
}

// 立即注册回调
const onSubmit = async () => {
  const params = {
      phone: phone.value,
      code: code.value,
      password: password.value
  }
  console.log(params);

  try {
      let result = await reqUserRegister(params);
      router.push('/login');
  } catch (error) {
      console.log(error);
  }
};
</script>

<style scoped lang="less">
.container {
  background: #fff;

  .bg_img {
      height: 205px;
      text-align: center;
      line-height: 40vh;

      .logoImg {
          width: 145px;
          height: 45px;
      }
  }

  .content {
      width: 100%;
      height: 372px;
  }

}
</style>